﻿using System;
using UnityEngine;

[RequireComponent(typeof(ParticleSystem))]
public class ParticleLight : MonoBehaviour
{
    private Light[] instances = new Light[0];
    private int lastCount;
    public Light lightPrefab;
    private ParticleSystem.Particle[] particles = new ParticleSystem.Particle[0];
    private ParticleSystem ps;
    private float[] times = new float[0];

    private void Awake()
    {
        this.ps = base.GetComponent<ParticleSystem>();
    }

    private void LateUpdate()
    {
        if (this.lightPrefab != null)
        {
            if (this.particles.Length < this.ps.maxParticles)
            {
                Array.Resize<ParticleSystem.Particle>(ref this.particles, this.ps.maxParticles);
            }
            if (this.instances.Length < this.ps.maxParticles)
            {
                Array.Resize<Light>(ref this.instances, this.ps.maxParticles);
            }
            if (this.times.Length < this.ps.maxParticles)
            {
                Array.Resize<float>(ref this.times, this.ps.maxParticles);
            }
            int particles = this.ps.GetParticles(this.particles);
            for (int i = 0; i < particles; i++)
            {
                ParticleSystem.Particle particle = this.particles[i];
                if (this.times[i] < particle.lifetime)
                {
                    if (this.instances[i] != null)
                    {
                        this.instances[i].Recycle<Light>();
                    }
                    this.instances[i] = this.lightPrefab.Spawn<Light>();
                    this.instances[i].gameObject.SetActive(true);
                }
                Light light = this.instances[i];
                if (light != null)
                {
                    light.transform.position = (this.ps.simulationSpace != ParticleSystemSimulationSpace.Local) ? particle.position : this.ps.transform.TransformPoint(particle.position);
                    light.color = (Color) particle.GetCurrentColor(this.ps);
                    light.intensity = light.color.a;
                }
                this.times[i] = particle.lifetime;
            }
            for (int j = particles; j < this.lastCount; j++)
            {
                if (this.instances[j] != null)
                {
                    this.instances[j].Recycle<Light>();
                }
            }
            this.lastCount = particles;
        }
    }

    private void OnDisable()
    {
        for (int i = 0; i < this.lastCount; i++)
        {
            if (this.instances[i] != null)
            {
                UnityEngine.Object.DestroyImmediate(this.instances[i].gameObject);
            }
        }
    }

    private void OnEnable()
    {
        this.OnDisable();
    }
}

